import subprocess
import time

# 配置参数
LOCUST_FILE = "locust_main.py"  # 替换为你的 Locust 脚本路径


def start_master():
    """启动 master 节点"""
    # # 打开新终端，执行 master 命令
    # cmd = f'locust -f {LOCUST_FILE} --master'
    # subprocess.Popen(
    #     ['cmd.exe', '/k', cmd],  # /k 表示执行命令后保持终端打开
    #     creationflags=subprocess.CREATE_NEW_CONSOLE  # 新建终端窗口
    # )
    # print("Master 节点已启动")
    # time.sleep(2)  # 等待 master 初始化


def start_worker(worker_id):
    """启动单个 worker 节点"""
    # 打开新终端，执行 worker 命令（指定 master 为本地）
    # cmd = f'locust -f {LOCUST_FILE} --worker --master-host=192.168.7.196'
    cmd = f'locust -f {LOCUST_FILE} --worker --master-host=localhost'
    subprocess.Popen(
        ['cmd.exe', '/k', cmd],
        creationflags=subprocess.CREATE_NEW_CONSOLE
    )
    print(f"Worker {worker_id} 已启动")


if __name__ == "__main__":
    # 1. 先启动 master
    # start_master()
    WORKER_COUNT =2   # 要启动的 worker 数量

    # 2. 再启动多个 worker
    for i in range(WORKER_COUNT):
        start_worker(i + 1)
        time.sleep(1)  # 间隔启动，避免冲突

    print(f"已启动{WORKER_COUNT} 个 worker")